﻿using System;
using System.Web.Security;
using System.Web.Services;
using System.Collections.Generic;
using System.Reflection;

namespace TripLOA.WebService
{
    public abstract class WsCore
    {
        /// <summary>
        /// Validate all parameters given in the input List. For each parameter the method try to parse the value (a string) into the given Type
        /// </summary>
        /// <param name="parameters">Input parameters with types</param>
        /// <returns>True if all parameters are valid, False if at least one of them is not valid</returns>
        public static bool ValidateParameters(List<WSParameter> parameters)
        {
            var a = new { id = 0 };

            foreach (var cell in parameters)
            {
                //Key: Type, Value: value
                Type type = cell.type;
                string value = cell.value;
                if (value == null) return false;

                System.Type[] arrTypes = new System.Type[2];
                arrTypes.SetValue(typeof(string), 0);
                arrTypes.SetValue(Type.GetType(type.ToString() + "&"), 1); //The type must be a reference (so must end with &)
                MethodInfo mInfo = type.GetMethod("TryParse", arrTypes);

                // The two parameters for TryParse method
                Object[] arrParms = new Object[2];
                arrParms.SetValue(value, 0);
                try
                {
                    bool success = (bool)mInfo.Invoke(null, arrParms);
                    if (!success) return false;
                }
                catch (Exception)
                {
                    //Error during method invocation: return false
                    return false;
                }
            }
            return true;
        }
    }

    public struct WSParameter
    {
        public string value;
        public Type type;
    }
}
